/**
 * ReverseString.java created by zhangzhidong 
 * at 下午4:11:21 2016年10月11日
 */
package algorithm;
public class ReverseString {
	  public String ReverseSentence(String str) {
			char []s = str.toCharArray();
	        boolean flag = false;
	        for(int i=0;i<s.length;i++){
	            if(s[i]==' '){
	            	flag = true;
	                break;
	            }
	        }
	        if(flag){
	            String re = re(s,0,s.length-1);
	            char ch [] = re.toCharArray();
	            int lb = 0;
	            int rb = -1;
	            for(int i = 0;i<=ch.length;i++){
	                if(i==ch.length ||ch[i]==' '){
	                    rb=i==0?i:(i-1);
	                    re(ch,lb,rb);
	                    lb = -1;
	                }else{
	                    lb = lb==-1?i:lb;
	                    rb = i;
	                }
	            }
	            return new String(ch);
	        }else{
	        	return str;
	        }
	        
	    }
	    public String re(char [] arr,int start,int end){
	       int i = start;
	       int j = end;
	        while(i<j){
				char temp = arr[i];
	            arr[i] = arr[j];
	            arr[j] = temp;
	            i++;
	            j--;
	        }
	        return new String(arr);
	        
	    }
	    
	/**
	 * 下午4:11:21 2016年10月11日
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println(new ReverseString().ReverseSentence("Hello world!"));

	}

}
